<script lang="ts" setup>
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router'

interface ConfItem {
  title: string
  path: string
  imageUrl?: string
  activeImageUrl?: string
  isCollapsed?: boolean
  children?: ConfItem[]
}

const props = defineProps<{
  conf: ConfItem
  isCollapsed: boolean
}>()

const route = useRoute()
const isOpen = ref(false)

// 判断当前菜单项是否激活（仅对没有子菜单的项）
const isActive = computed(() => {
  return !props.conf.children?.length && route.path === props.conf.path
})

// 处理点击图片事件
const handleImageClick = (event: Event) => {
  if (props.isCollapsed && props.conf.children?.length) {
    // event.stopPropagation()
    isOpen.value = !isOpen.value
  }
}
</script>

<template>
  <div>
    <!-- 有子菜单的情况（主菜单） -->
    <el-sub-menu v-if="conf.children" :index="conf.path" class="el-sub-menu"
      :popper-class="isCollapsed ? 'hidden-popper' : ''" :open="isOpen">
      <template #title>
        <img :src="conf.imageUrl" alt="" class="menu-item-img" @click="handleImageClick" />
        <span v-if="!isCollapsed" style="color: white;">{{ conf.title }}</span>
      </template>
      <el-menu-item v-for="item in conf.children" :key="item.path" :index="item.path" class="el-menu-item"
        style="background-color: rgb(13, 21, 32);">
        <span style="color: white;">{{ item.title }}</span>
      </el-menu-item>
    </el-sub-menu>

    <!-- 无子菜单的情况（单一项） -->
    <el-menu-item v-else :index="conf.path" class="el-menu-item" style="background-color: rgb(13, 21, 32);"
      :class="{ 'is-active': isActive }">
      <img :src="conf.imageUrl" alt="" class="menu-item-img" />
      <span v-if="!isCollapsed" style="color: white;">{{ conf.title }}</span>
    </el-menu-item>
  </div>
</template>

<style scoped>
/* 仅添加没有子菜单时的高亮样式 */
:deep(.el-menu-item.is-active) {
  background-color: var(--el-color-primary) !important;
}

/* 保持原有的样式不变 */
.menu-item-img {
  width: 16px;
  height: 16px;
  margin-right: 8px;
  vertical-align: middle;
  transition: all 0.3s ease;
  cursor: pointer;
}

:deep(.el-sub-menu__icon-arrow) {
  color: white !important;
  display: v-bind('isCollapsed ? "none" : "block"');
}

/* 去掉主菜单划过时的样式变化 */
:deep(.el-sub-menu .el-sub-menu__title:hover) {
  background-color: transparent !important;
}
</style>

<style>
/* 全局样式 - 用于隐藏折叠时的弹出菜单 */
.hidden-popper {
  display: none !important;
}
</style>